Skip to content

feat(knowledge-turso, knowledge-pgvector): hybrid search, a keyword leg merged with the vector leg by RRF - #38037

Merged
objectstack-fleet[bot] merged 5 commits into
mainfrom
claude/area-o1C-37974
Nov 27, 2026
Merged

objectstack-fleet[bot] merged 5 commits into
mainfrom
claude/area-o1C-37974

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP
Fixes #37974

Clause-②: no
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:在知识检索里搜订单号、型号(如 X-200)、人名或「出差」这类短词时,含这些词的段落会排进结果,之前只靠语义向量常被排到前几名之外。
  • 为什么做:知识平台总卡下的检索质量子卡,让元数据开发平台上任何知识源(不只制度库)都能按精确词找到内容。
  • 出错会怎样:检索结果的排序和分数会变;关键词一路出错时最坏是排序变差或检索报错,权限复核不受影响,撤回本次合并即可恢复原样。
  • 要你做什么:无。

What changes

Both open knowledge stores now search with two legs and merge them by reciprocal rank fusion (RRF, k = 60, each leg ranks at most topK) inside the adapter, so before the knowledge service re-checks each hit as the caller.

  • Terms. The query is split at white space and punctuation; a hyphen, dot, slash, underscore, #, @ or + inside a term keeps it whole (X-200, v1.2, a/b), at most 16 terms. A passage's keyword score is the sum, over the terms it holds, of the term's BM25 inverse document frequency among the rows in scope (binary term frequency), so a word most passages hold weighs little. Keyword ties are ranked by cosine distance, and fused ties go to the better vector rank, so the keyword leg never reorders by chunk id what the vector leg ranks.
  • knowledge-turso. A term of three characters or more is one quoted FTS5 phrase (an inner double quote doubled), so X-200 is never FTS5 syntax. It is matched in a contentless trigram FTS5 table beside each passage table (TABLE-fts), keyed through a map table (TABLE-kw, an INTEGER PRIMARY KEY, so a VACUUM cannot renumber it) and kept in step by three triggers on the passage table (insert, delete, update of chunk_id or content), inside the statement that writes the passage. A shorter term (「出差」) is matched by content LIKE over the rows in scope. The keyword index is made with the passage table and dropped with it (generation swap, completeBuild, dropSource). Its names hold a hyphen, which no source id, generation table or object name can hold; an object under one of those names that the store did not make is refused SERVICE_UNAVAILABLE, naming it, and never dropped.
  • knowledge-pgvector. A word of three characters or more is phraseto_tsquery('simple', term) on to_tsvector('simple', content), served by a GIN expression index (knowledge_vec_dWIDTH_content_tsv): no column added, no row rewritten. A shorter term, or one holding a Han, kana or Hangul character, is matched by content ILIKE: measured on PostgreSQL 16, the simple parser keeps a run of Han characters as one word ('出差住宿标准每晚三百元'), so a tsvector phrase could never find 「住宿标准」 inside it. Both legs run in one statement (one snapshot), each behind the existing active-generation guard.
  • One WHERE. The organization filter, the record scope and the metadata filter are built once and applied in both legs (and in the inverse-document-frequency counts), before either ranks.
  • An index made before this PR still answers. turso: the first search of a passage table without a keyword index builds it from the table's rows in one write transaction (shape-checked first), then answers from it. pgvector: the first write or search of a width runs CREATE INDEX IF NOT EXISTS; a concurrent loser re-reads the catalogue and goes on. Both pinned.
  • Score. A hit's score is now the fused rank normalized to (0, 1]: 1 for first in both legs, 0.5 for first in one alone. It was the cosine similarity.
  • Docs: both READMEs, content/docs/ai/knowledge-rag.mdx (retrieval and both store sections), and the two Search bullets plus the adapter table of content/docs/protocol/knowledge.mdx, which this change made incomplete (outside the claim's file surface; declared in the report).

Serial with #37957. That card adds a visible-ids pre-filter to the search options and is not started. Whichever lands second applies its filter or leg to both legs: here the one WHERE (inScope in both adapters) is the single place a new filter goes, and it already feeds both legs and the counts.

Read first (by risk)

  1. packages/plugins/knowledge-turso/src/sql.ts keywordIndexDdl: the triggers and the backfill. A trigger that drifts from the passage table leaves the contentless index wrong silently (the FTS5 delete command needs the indexed text, which old.content holds).
  2. packages/plugins/knowledge-turso/src/turso-adapter.ts searchAttempt: the shared inScope in vec, cand and stats; the parameter numbering (?1 is the vector in both legs).
  3. packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts searchAttempt and ensureKeywordIndex: the one statement and the first-search index build.

Two-minute check

cd packages/plugins/knowledge-turso && pnpm exec vitest run --maxWorkers=2 src/__tests__/acceptance.test.ts -t "hybrid search" prints 16 passed (8 cases on :memory: and on a file: URL).

Tests

New pins (turso: acceptance.test.ts, top-level describe; pgvector: acceptance.live-postgres.test.ts, top-level describe)
  • An exact code in a question: the fixture asserts the vector leg alone ranks the code's passage 7th of 7; the hybrid search returns it within topK = 3; the code alone answers it first with score 1 (both legs). Both stores.
  • 「出差」 (2 characters) and 「住宿标准」 (inside an unsplit run) hit: turso by LIKE and the trigram index, score 1; pgvector by ILIKE, score 0.5 (the fake embedder holds a Han run as one word, so only the keyword leg ranks them).
  • The organization filter, a record scope and the metadata filter each exclude an out-of-scope passage that holds the query's code and short term, while the in-scope keyword match still ranks. Both stores.
  • turso: every query string tried as FTS5 syntax (X-200, "A", NEAR(the, OR, * pump^2, col:umn, -x, a AND b NOT c) answers; the keyword index follows a rewrite, a delete, a generation swap and dropSource; a table without a keyword index gets one at its first search, 7 map rows from 7 passages, and stays in step after; an object table under TABLE-kw refuses the build, naming it, and keeps its row.
  • pgvector: the GIN index dropped, a new adapter's first search rebuilds it and answers; with sequential scans priced out the plan names the index.
  • turso: the term splitter, the LIKE escape and the FTS5 phrase quoting, as a unit.
Readings (head d0340b7 for both suites; ablations on b2d204a before the merge of main, which touched no knowledge package)
  • knowledge-turso vitest run --maxWorkers=2: Test Files 4 passed (4), Tests 201 passed (201).
  • knowledge-pgvector vitest run --maxWorkers=2 against a private PostgreSQL 16 with pgvector (UTF8 database): Test Files 8 passed, Tests 96 passed; reconcile-purge and reindex-real-driver did not load (@objectstack/metadata-protocol / @objectstack/objectql unbuilt here) — NOT MEASURED locally; neither file calls search.
  • Ablations, each a mutation on disk, the pin run, restored from HEAD, the pins green again (turso 16/16, pgvector 4/4):
    • keyword leg off (terms = []): exact-code pin red in both stores, "expected [ …(3) ] to include 'Seal kit for model X-200, part 7731.'".
    • LIKE fallback off (terms under 3 characters dropped): 2-character pin red, turso "expected 0.5 to be 1", pgvector "expected [] to deeply equal [ [ 'zh_short:1', 0.5 ] ]".
    • filter dropped from the keyword leg only: scope pin red in both stores, "expected [ 'kw_scope:out' ] to deeply equal []".

Acceptance notes

  • BrightRule eval set: NOT MEASURED. The objectstack-ai/brightrule repository is not attached to this session (the API answers 403, access not enabled), and the eval needs a real embedding provider. RRF reorders the vector leg's results whenever the keyword leg ranks something, so this is the reading that would show a regression; it belongs to whoever runs that eval next.
  • Score semantics changed. KnowledgeHit.score from these two stores is the normalized fused rank, no longer the cosine similarity. The knowledge service sorts hits across sources by score, so a deployment mixing these stores with another adapter now compares a fused rank with that adapter's score. No threshold on score exists in the service today.
  • Cost. A LIKE or ILIKE term scans the rows in scope (the vector leg is already an exact scan). In pgvector a common word makes most rows candidates, and each candidate's tsvector is computed once for the per-term counts. No CJK word segmentation: a Chinese question without spaces or punctuation is one term, so the keyword leg finds a code, a name or a phrase as written and the vector leg answers the meaning.
  • turso uses ln(), an SQLite math function: present in the libSQL client build (SQLite 3.45.1, measured); a remote Turso server is not measured.
  • pgvector's first-search index build blocks writes to that width's table while CREATE INDEX runs, once.

Verification

Local gate families (dispatch-gates --commands on d0340b7; lock saturated, so run outside it as check gates are)

Generated by Claude Code

@github-actions github-actions Bot added size/l documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 27, 2026
@github-actions

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 2 package(s): @objectstack/knowledge-pgvector, @objectstack/knowledge-turso, touching 29 documentable anchor(s). ⚠️ 2 changed file(s) yielded no anchor (packages/plugins/knowledge-pgvector/README.md, packages/plugins/knowledge-turso/README.md), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

1 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:

  • content/docs/ai/knowledge-rag.mdx (via c.content (literal, a string literal in searchAttempt))
What this run could not see
  • 2 changed file(s) yielded no anchor (packages/plugins/knowledge-pgvector/README.md, packages/plugins/knowledge-turso/README.md) — pages documenting those are invisible to this run
  • 2 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 69 of 252 client-bound route-ledger rows — the other 183 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 183: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 124 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 2 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json cb3f8b9538d167460d3a67c5201a1e6315e936e2 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 15940bf430ebdecd439c2e1e4dfd0514868c1c3a — the merge of head d0340b7b522d45fe8323611654a0a259f12f102b into base cb3f8b9538d167460d3a67c5201a1e6315e936e2, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 15940bf430ebdecd439c2e1e4dfd0514868c1c3a && git checkout 15940bf430ebdecd439c2e1e4dfd0514868c1c3a
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin cb3f8b9538d167460d3a67c5201a1e6315e936e2 d0340b7b522d45fe8323611654a0a259f12f102b && git checkout -B drift-repro cb3f8b9538d167460d3a67c5201a1e6315e936e2 && git merge --no-ff d0340b7b522d45fe8323611654a0a259f12f102b

node scripts/docs-audit/affected-docs.mjs --json cb3f8b9538d167460d3a67c5201a1e6315e936e2

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs cb3f8b9538d167460d3a67c5201a1e6315e936e2 → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-elon-musk · session_016WV4czzx9dtSEm3jWWL9c3

L1 verdict (L1-a): ACCEPT at head d0340b7b522d45fe8323611654a0a259f12f102b (Fixes #37974). Full read · 2026-11-27T19:23Z

席位核对

Shape and gates. 11 files, +915/-61, in knowledge-turso, knowledge-pgvector and the docs. Not governed. Clause-②: no · Metadata-protocol: none. No contract review is owed: no path is a published-schema or governed face, and the declaration is no. Check-runs at this reading are 38 success, 15 expected skip, 0 failed, and Test Core (3/10) pending. The area lands only once every check is green.

The score question. The score is now the fused RRF rank normalised to (0, 1] instead of cosine similarity, and Clause-②: no still holds. KnowledgeHitSchema (packages/spec/src/ai/knowledge-document.zod.ts:141) already says score semantics are "adapter-specific (cosine / dot product / hybrid blend); higher is always better, normalised to [0, 1] when feasible". IKnowledgeAdapter.search promises only descending order. No consumer in this repo compares a knowledge score against a threshold. Cross-adapter comparability (a fused 0.5 beside a memory adapter's cosine) is named in the changeset. That is the right place for it: the spec already disclaims it, and a deployment mounts one store.

What I read myself.

  • Scope in both legs. One inScope WHERE (organization filter, record scope, metadata filter) feeds the vector leg, the keyword candidates and the IDF counts, in both stores. So the keyword leg cannot surface or weigh a row outside the caller's scope before the service's re-check.
  • No query syntax. turso binds each 3+-character term as an FTS5 phrase (ftsPhrase doubles inner quotes) and shorter terms as an escaped LIKE … ESCAPE '\'. pgvector binds phraseto_tsquery('simple', $n) and escaped ILIKE. Every value is a parameter.
  • Index upkeep (turso). Writes go through ON CONFLICT (chunk_id) DO UPDATE, so the UPDATE OF chunk_id, content trigger keeps the contentless FTS5 entry in step, and nothing depends on REPLACE firing delete triggers. Every keyword-index name holds a hyphen, so it cannot collide with a store or object table. A foreign object under one is refused like fix(knowledge-turso): never drop a table the store did not make, and check knowledge_generation's shape at ready() #38014's passage-table guard (assertKeywordIndexOurs). transaction() is not routed through queued, so ensureKeywordIndex inside the queue cannot deadlock.
  • Fusion. Each leg ranks at most topK, and fuse sums 1/(60+rank), divides by the both-first score, breaks ties by vector rank then chunk id, and slices to topK.

Nits, not owed.

  • N1 (pgvector): the lazy CREATE INDEX IF NOT EXISTS … USING gin at first search is not CONCURRENTLY, so it holds a write-blocking lock on the width's shared passage table while it builds. If creation fails and no index exists, the whole search is refused, not just the keyword leg. With no production tenants this is acceptable; a sentence in the README's operator notes would name it.
  • N2: the PR body's Verification section predates the closure build, and dev report 7226371724 supersedes it. Align it if the head moves.
  • BrightRule eval NOT MEASURED, and the serial order with service-knowledge: search pre-filters by the caller's visible record ids within the record scope #37957 (whichever lands second filters both legs), are declared. I take them as stated.

Landing: not governed, so the area lands it after ACCEPT, with all checks green.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP

Landing · area o1-C · head d0340b7b52 · 2026-11-27T19:25Z · ACCEPT → PR #38037 comment 7226483295 (L1-a)

Probe Reading
check-runs at d0340b7b52 40 success · 15 expected skip · 0 failed · 0 pending · mergeable_state clean
check-governed-merges.mjs --pr 38037 NOT governed · +915 / −61
landing-k.mjs --pr 38037 K = 4 < 15

State: ready + auto-merge; #37974 closes on merge via Fixes. Clause-②: no, not a (narrowing); L1 found no L2 owed (KnowledgeHitSchema already leaves score semantics to the adapter). The PR body's Verification section predates the closure build; the dev report on #37974 (comment 7226371724) is the current record. Not owed, noted: the pgvector GIN index is built lazily at first write or search, non-concurrently.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/l tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

knowledge-turso/pgvector: hybrid search, a keyword leg (FTS5 trigram / tsvector) merged with the vector leg by RRF

2 participants